<?php

namespace app\job\event;

use GatewayWorker\Lib\Gateway;

/**
 * 订单事件管理
 */
class RefundOrder
{
    // 模型
    private $model;

    // 应用id
    private $appId;

    /**
     * 执行函数
     */
    public function handle()
    {
        //定时任务5秒钟执行一次，消息推送30秒推送一次
        $Redis = new \think\cache\driver\Redis(config('cache.stores.redis'));
        $refund_order_push_time = $Redis->get('refund_order_push_time');
        if($refund_order_push_time){
            if($refund_order_push_time >= 6){
                $refund_order_push_time = 1;
                $Redis->set('refund_order_push_time', $refund_order_push_time+1);
            }else{
                $Redis->set('refund_order_push_time', $refund_order_push_time+1);
            }

        }else{
            $refund_order_push_time = 1;
            $Redis->set('refund_order_push_time', $refund_order_push_time);
        }

        if($refund_order_push_time != 1){
            return;
        }
        try {
            log_write('refund_order_push_time Init : ==========》refund_order_push_time------init----p>>'.$refund_order_push_time, 'task');
            $model = new \app\common\model\order\Order();
            $list = $model->where('is_order_refund', '=', 1)->select();

            foreach ($list as &$item) {
                $this -> pushMsg($item['store_clerk_id']);
            }

        } catch (\Throwable $e) {
            echo 'ERROR ORDER: ' . $e->getMessage() . PHP_EOL;
            log_write('refund_order_push_time TASK : __ ' . $e->getMessage(), 'task');
        }
        return true;
    }

    /**
     * 消息推送
     * pushMsg
     * @param $uid
     * void
     * @return void
     * @Author kevin
     * @date 2024/5/11 10:46
     */
    private function pushMsg($uid)
    {
        Gateway::$registerAddress = '127.0.0.1:1238';
        file_put_contents('refund_client_ids.txt',$uid.'-----'.date('Y-m-d H:i:s') . "\r\n", FILE_APPEND);
        $client_ids = Gateway::getClientIdByUid($uid); //通过uid 获取client_id 返回的是数组;
        file_put_contents('refund_client_ids.txt',var_export($client_ids,true) . "\r\n", FILE_APPEND);
        if(!$client_ids){
            return ;
        }
        $message = '{"type":"refund_order","content":"您有新的售后订单"}';
        // 向当前client_id发送数据
        foreach ($client_ids as $value){
            Gateway::sendToClient($value, "$message\r\n");
        }
        return;
    }

}
